<!DOCTYPE html>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>1-3 拖拽Div</title>
	<style>
		*{
			margin: 0;
			padding: 0;
		}
		#div1{
			width: 100px;
			height: 100px;
			background-color: red;
			position: absolute;
		}
		.box{
			border: 1px solid black;
			position: absolute;
		}
	</style>
	<script type="text/javascript">
		window.onload=function() {
			var hezi=document.querySelector("div"),
				leftX=0,
				topX=0;

			hezi.onmousedown=function(ev){
				var oEvent=ev||event;
				leftX=oEvent.clientX-hezi.offsetLeft;
				topX=oEvent.clientY-hezi.offsetTop;
				//拖拽实线框而不是元素
				var oBox=document.createElement('div');
				oBox.className="box";
				oBox.style.width=hezi.offsetWidth+'px';
				oBox.style.height=hezi.offsetHeight+'px';
				oBox.style.left=hezi.offsetLeft+'px';
				oBox.style.top=hezi.offsetTop+'px';
				//给页面添加一个元素，这个元素叫oBox
				document.body.appendChild(oBox);
				document.onmousemove=function(ev){
					var oEvent=ev||event,
						x=oEvent.clientX-leftX,
						y=oEvent.clientY-topX;
					//不让Div出四周的边框造成BUG,并且添加四周20px内磁性吸附
					if (x<20) {
						x=0;
					}
					else if (x>document.documentElement.clientWidth-hezi.offsetWidth-20) {
						x=document.documentElement.clientWidth-hezi.offsetWidth;
					}
					if (y<20) {
						y=0;
					}
					else if (y>document.documentElement.clientHeight-hezi.offsetHeight-20) {
						y=document.documentElement.clientHeight-hezi.offsetHeight;
					}
					
					oBox.style.left=x+'px';
					oBox.style.top=y+'px';
				};

				document.onmouseup=function(){
					document.onmousemove=null;
					document.onmouseup=null;
					hezi.style.left=oBox.offsetLeft+'px';
					hezi.style.top=oBox.offsetTop+'px';
					document.body.removeChild(oBox);
				};
			};
		};
	</script>
</head>
<body>
	<div id="div1"></div>
</body>
</html>